import { getAllFile, downloadFile, deleteFile, importFile } from '@/api/file.js';
import { getAllPF, importPF, deletePF, getImportedPF, removePF } from '@/api/data.js';
import pako from 'pako';

export default {
    data() {
        return {
            tableData: [],
            tableList: 0,
            search: '',
            unactionable: false,    // 按钮是否可以点击
            table_loading: false,   // 加载表格

            processedData: [],  // 处理后的数据
            pf_loading: false,  // 加载处理后的数据

            importedData: [],   // 导入系统的数据
            id_loading: false,  // 加载导入的数据
        }
    },
    methods: {
        // 获取数据集
        getAllFile() {
            this.pf_loading = true;
            // 获取数据
            getAllPF(this.user_id).then(({ data }) => {
                // 先清除数据
                this.processedData = [];
                const pf = data.map(item => ({
                    id: item.id,
                    filename: item.filename,
                    size: item.size,
                }));
                this.processedData.push(...pf);

                this.pf_loading = false;
            }).catch(error => {
                this.pf_loading = false;
            }).finally({});
        },
        // 获取所有导入数据集
        getAllIFile() {
            this.id_loading = true;
            // 获取数据
            getImportedPF(this.user_id).then(({ data }) => {
                // 先清除数据
                this.importedData = [];
                const ifs = data.map(item => ({
                    id: item.id,
                    filename: item.filename,
                    size: item.size,
                }));
                this.importedData.push(...ifs);

                // 获取菜单的数据，存入store中
                if (this.importedData.length === 0) {
                    this.$store.commit('setImport', false);
                } else {
                    this.$store.commit('setImport', true);
                }

                this.id_loading = false;
            }).catch(error => {
                this.id_loading = false;
            }).finally({});
        },
        // 导入数据集
        sendPFtoSystem() {
            const records = this.$refs.processedData.getCheckboxRecords();
            const fileIds = records.map((file) => file.id);

            this.$notify.info({
                title: '消息',
                message: '正在将数据集导入系统',
                position: 'bottom-right',
                duration: 4000
            });

            if (fileIds.length !== 0) {
                importPF(fileIds).then(({ data }) => {
                    console.log(data);

                    // 进行gzip解压缩
                    const inflatedData = pako.inflate(data, { to: 'string' });
                    data = JSON.parse(inflatedData);

                    console.log(data);

                    // 更新导入的数据集列表
                    this.getAllIFile();

                    // 清空选中的复选框
                    this.$nextTick(() => {
                        this.$refs.processedData.clearCheckboxRow();
                    });

                    // 获取菜单的数据，存入store中
                    this.$store.commit('setImport', true);

                    this.$store.commit('getResult', data);

                    this.$notify({
                        title: '成功',
                        message: '数据集导入成功',
                        type: 'success',
                        position: 'bottom-right',
                        duration: 3000,
                    });
                }).catch(error => {
                    console.log(error);
                    this.$notify.error({
                        title: '错误',
                        message: '数据集导入失败',
                        position: 'bottom-right',
                        duration: 3000,
                    });
                }).finally({});
            }
        },
        // 删除数据集
        deletePF() {
            const records = this.$refs.processedData.getCheckboxRecords();
            const fileIds = records.map((file) => file.id);

            if (fileIds.length !== 0) {
                deletePF(fileIds).then(({ data }) => {

                    // 更新导入的数据集列表
                    this.getAllFile();
                    this.getAllIFile();

                    // 剔除fileIds中出现在importedData的id
                    var newImportedData = this.importedData.filter(data => !fileIds.includes(data.id));
                    if (JSON.stringify(newImportedData) !== JSON.stringify(this.importedData)) {
                        // 从剔除后的importedData中提取新的id生成新的fileIds
                        const newFileIds = newImportedData.map(data => data.id);
                        if (newFileIds.length !== 0) {
                            importPF(fileIds).then(({ data }) => {
                                this.$store.commit('getResult', data);

                                // 更新导入的数据集列表
                                this.getAllIFile();

                            }).catch(error => {
                            }).finally({});
                        }
                    }

                    this.$notify({
                        title: '成功',
                        message: '数据集删除成功',
                        type: 'success',
                        position: 'bottom-right',
                        duration: 2000,
                    });
                }).catch(error => {
                    console.log(error);
                    this.$notify.error({
                        title: '错误',
                        message: '数据集删除失败',
                        position: 'bottom-right',
                        duration: 2000,
                    });
                }).finally({});
            }
        },
        // 删除导入的数据集 
        deletePFFromSystem() {
            const records = this.$refs.importedData.getCheckboxRecords();
            const fileIds = records.map((file) => file.id);

            if (fileIds.length !== 0) {
                removePF(fileIds).then(({ data }) => {
                    console.log(data);

                    // 进行gzip解压缩
                    const inflatedData = pako.inflate(data, { to: 'string' });
                    data = JSON.parse(inflatedData);

                    this.$store.commit('getResult', data);

                    // 更新导入的数据集列表
                    this.getAllIFile();

                    this.$notify({
                        title: '成功',
                        message: '数据集剔除成功',
                        type: 'success',
                        position: 'bottom-right',
                        duration: 3000,
                    });
                }).catch(error => {
                    this.$notify.error({
                        title: '错误',
                        message: '数据集剔除失败',
                        position: 'bottom-right',
                        duration: 3000,
                    });
                }).finally({});
            }
        },

        formatFileSize(bytes) {
            const megabytes = bytes / (1024 * 1024);
            return megabytes.toFixed(3) + ' MB';
        },
        // 从后端获取文件信息并更新数据
        fetchDataFromBackend() {
            this.table_loading = true;
            // 获取数据
            getAllFile(this.user_id).then(({ data }) => {
                // 先清除数据
                this.tableData = [];
                const files = data.map(item => ({
                    size: this.formatFileSize(item.size),
                    name: item.filename,
                    id: item.id,
                }));
                this.tableData.push(...files);
                this.tableList = data.length;

                this.table_loading = false;
            }).catch(error => {
                this.table_loading = false;
            })
        },
        // 处理文件
        handleImport(index, row) {
            console.log('导入文件进系统');
            // this.unactionable = true;

            // 更新导入状态
            var currIndex = 1;
            if (this.processedData.length > 0) {
                currIndex = this.processedData[this.processedData.length - 1].id + 1;
            }
            this.processedData.push({ id: currIndex, filename: row.name, size: 'loading' });

            this.$notify.info({
                title: '消息',
                message: '正在处理文件',
                position: 'bottom-right',
                duration: 4000
            });

            importFile(row.id, this.user_id).then(({ data }) => {
                console.log(data);
                const inflatedData = pako.inflate(data, { to: 'string' });
                data = JSON.parse(inflatedData);
                console.log(data);

                if (data.code === 200) {
                    console.log(data);

                    // this.unactionable = false;
                    console.log('success');
                    this.$notify({
                        title: '成功',
                        message: '文件处理成功',
                        type: 'success',
                        position: 'bottom-right',
                        duration: 3000
                    });
                } else {
                    // this.unactionable = false;
                    console.log(data);
                    this.$notify.error({
                        title: '错误',
                        message: '没有找到文件',
                        position: 'bottom-right',
                        duration: 3000
                    });
                }

                // 找到 id 为 currIndex 的对象索引
                const index = this.processedData.findIndex(item => item.id === currIndex);
                this.processedData[index].size = data['data'].length;
            }).catch(error => {
                console.log(error);
                // this.unactionable = false;
                this.$notify.error({
                    title: '错误',
                    message: '文件处理失败',
                    position: 'bottom-right',
                    duration: 3000
                });

                this.processedData.pop();
            });
        },
        // 下载文件
        handleDownload(index, row) {
            console.log('下载文件');

            // 调用文件下载接口
            downloadFile(row.id).then(({ data }) => {
                // 下载文件
                const url = window.URL.createObjectURL(new Blob([data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', row.name); // 设置下载文件名
                document.body.appendChild(link);
                link.click();

                this.$notify({
                    title: '成功',
                    message: '文件下载成功',
                    type: 'success',
                    position: 'bottom-right',
                    duration: 2000
                });
            }).catch(error => {
                // this.$message.error('文件下载失败');
                this.$notify.error({
                    title: '错误',
                    message: '文件下载失败',
                    position: 'bottom-right',
                    duration: 2000
                });
            })
        },
        // 删除文件
        handleDelete(index, row) {
            console.log('删除文件');
            deleteFile(row.id).then(({ data }) => {
                console.log(data)
                // this.$message.success('文件删除成功');
                this.$notify({
                    title: '成功',
                    message: '文件删除成功',
                    type: 'success',
                    position: 'bottom-right',
                    duration: 2000
                });

                this.fetchDataFromBackend()
            }).catch(error => {
                // this.$message.error('文件删除失败');
                this.$notify.error({
                    title: '错误',
                    message: '文件删除失败',
                    position: 'bottom-right',
                    duration: 2000
                });
            })
        },
        // 文件添加成功
        handleFileAdd() {
            console.log('文件添加成功');
            // 将新上传的文件信息添加到文件列表中
            this.fetchDataFromBackend()
            this.$notify({
                title: '成功',
                message: '文件上传成功',
                type: 'success',
                position: 'bottom-right',
                duration: 2000
            });
        },
        isLoading({ row }) {
            return row.size != 'loading'
        }
    },
    mounted() {
        // 页面挂载时从后端获取数据并更新
        this.fetchDataFromBackend();
        this.getAllFile();
        this.getAllIFile();
    },
    computed: {
        result() {
            return this.$store.state.processedData.result
        },
        user_id() {
            return this.$store.state.userData.userData.user_id;
        }
    }
}